import {
  mapGetters,
  mapMutations,
  mapActions
} from 'vuex';
import {
  playMode
} from 'common/js/config';
import {
  shuflle
} from 'common/js/util';
import SearchList from 'base/search-list';

export const playlistMixin = {
  computed: {
    ...mapGetters(['playList'])
  },
  activated() {
    this.handlePlayList(this.playList)
  },
  mounted() {
    this.handlePlayList(this.playList)
  },
  watch: {
    playList(newVal) {
      this.handlePlayList(newVal)
    }
  },
  methods: {
    handlePlayList() {
      throw new Error('发生错误了，没有 handlePlayList 方法')
    }
  }
}

export const playerMixin = {
  computed: {
    iconMode() {
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    },
    ...mapGetters(["mode", 'sequenceList', 'currentSong', 'playList', 'favoriteList'])
  },
  methods: {
    // 切换模式
    changeMode() {
      const mode = (this.mode + 1) % 3
      this.setPlayMode(mode)

      let list = null
      if (mode === playMode.random) {
        list = shuflle(this.sequenceList)
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },
    // 重新设置索引
    resetCurrentIndex(list) {
      let index = list.findIndex((item) => {
        return item.id === this.currentSong.id
      })
      this.setCurrentIndex(index)
    },
    // 设置收藏类名
    classFavorite(song) {
      if (this.booleansFavorite(song)) {
        return 'icon-favorite'
      }
      return 'icon-not-favorite'
    },
    // 点击收藏事件
    clickFavorite(song) {
      if (this.booleansFavorite(song)) {
        this.delateFavoriteList(song)
      } else {
        this.saveFavoriteList(song)
      }
    },
    // 判断是否收藏
    booleansFavorite(song) {
      const index = this.favoriteList.findIndex((item) => {
        return item.id === song.id
      })
      return index > -1
    },
    ...mapMutations({
      setPlayingState: 'SET_PLAYING_STATE',
      setCurrentIndex: 'SET_CURRENT_INDEX',
      setPlayMode: "SET_PLAY_MODE",
      setPlayList: "SET_PLAYLIST"
    }),
    ...mapActions(['delateFavoriteList', 'saveFavoriteList'])
  }
}


// 搜索公共
export const searchMixin = {
  data() {
    return {
      query: '',
      refreshDelay: 100
    }
  },
  computed: {
    ...mapGetters(['searchHistory'])
  },
  components: {
    SearchList
  },
  methods: {
    changeQyery(item) {
      this.query = item
    },
    changeScroll() {
      this.$refs.searchBoxRef.scrollBlur()
    },
    saveSearch() {
      this.saveSearchHistory(this.query)
    },
    changeSearch(item) {
      this.$refs.searchBoxRef.setQuery(item)
    },
    ...mapActions(['saveSearchHistory', 'delateSearchHistory'])
  }
}
